package com.example.myapplication.test;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.myapplication.OnDateDelayAdapter;
import com.example.myapplication.R;
import com.example.myapplication.Utils;
import com.example.myapplication.dataBase.SubjectsDatabaseHelper;
import com.example.myapplication.models.MySubject;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.models.SubjectRepertory;
import com.example.myapplication.parasActivity;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.IWeekView;
import com.zhuangfei.timetable.listener.OnDateBuildAapter;
import com.zhuangfei.timetable.listener.OnItemBuildAdapter;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.utils.ScreenUtils;
import com.zhuangfei.timetable.view.WeekView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketImpl;
import java.net.URL;
import java.nio.channels.AlreadyBoundException;
import java.nio.channels.MulticastChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class getBackActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String url = "https://xkcts.ucas.ac.cn:8443/course/termSchedule";
    //public static final String AD_URL="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545749786636&di=fd5483be8b08b2e1f0485e772dadace4&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F5f9fae85770bb289f790e08d778516d128f0492a114a8-TNyOSi_fw658";
    public static final String cookie="SESSION=NTc5NDM5NWMtMTI4ZC00YTY1LTk2MDMtM2U5MTY1NWM1ZTU3";
    //控件
    TimetableView mTimetableView;
    WeekView mWeekView;

    Button button;
    LinearLayout layout;
    TextView titleTextView;

    List<MySubject> mySubjects = new ArrayList<>();// 所有课程
    List<MySubject> Subjects_forchoose = new ArrayList<>();// 课程 视图只占一个格子
    List<MySubject> chooseSubjects = new ArrayList<>();// 选择的课程
    List<String[]> courses;
    List<String> categoryList = new ArrayList<>();
    List<String> depIdList = new ArrayList<>();
    List<String> termList = new ArrayList<>();

    public SubjectsDatabaseHelper Subjects_database;


    //记录切换的周次，不一定是当前周
    int target = -1;
    AlertDialog alertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_func);


        titleTextView = findViewById(R.id.id_title);
        layout = findViewById(R.id.id_layout);
        button = findViewById(R.id.id_more);

        String category="3";
        String deptId="985";
        String termId="74470";

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopmenu();
            }
        });
//        mySubjects = SubjectRepertory.loadDefaultSubjects();
//        chooseSubjects = SubjectRepertory.loadDefaultSubjects();
//        chooseSubjects.clear();
        Subjects_database = new SubjectsDatabaseHelper(this,"Subjects.db",null,2);
        String COL_1 = "ID";
        String COL_2 = "NAME";
        String COL_3 = "TEACHER";
        String COL_4 = "ROOM";
        String COL_5 = "WEEKLIST";
        String COL_6 = "START";
        String COL_7 = "STEP";
        String COL_8 = "DAY";
        String COL_9 = "TAG";
        String COL_10 = "TERM";
        Cursor cursor = Subjects_database.getAllData();
        while (cursor.moveToNext()){
            String name = cursor.getString(cursor.getColumnIndex(COL_2));
            String teacher = cursor.getString(cursor.getColumnIndex(COL_3));
            String room = cursor.getString(cursor.getColumnIndex(COL_4));
            String weeklist = cursor.getString(cursor.getColumnIndex(COL_5));
            int start = cursor.getInt(cursor.getColumnIndex(COL_6));
            int step = cursor.getInt(cursor.getColumnIndex(COL_7));
            int day = cursor.getInt(cursor.getColumnIndex(COL_8));
            String term = cursor.getString(cursor.getColumnIndex(COL_10));

            chooseSubjects.add(new MySubject(term,name,room,teacher, Arrays.stream(weeklist.split(",")).map(Integer::parseInt).collect(Collectors.toList()), start,step,day,-1,null));

        }

        layout.setOnClickListener(this);
        initTimetableView(chooseSubjects);
        //buildItemText();
        //hideNonThisWeek();
        String url2 = "https://xkcts.ucas.ac.cn:8443/course/ajax/querySubDept";
        Intent intent = getIntent();
        if(intent.hasExtra("category")){
            category = intent.getStringExtra("category");
            deptId = intent.getStringExtra("deptId");
            termId = intent.getStringExtra("termId");
        }

        new FetchPageTask().execute(url,category,deptId,termId);
//        FetchPageTask depTask = new FetchPageTask();
//        depTask.execute(url2);

        //new FetchPageTask().execute();

        requestData();
    }
    private class FetchPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... voids) {
            //String url = "https://xkcts.ucas.ac.cn:8443/course/termSchedule";
            String url = voids[0];
            //String cookie = "SESSION=NTc5NDM5NWMtMTI4ZC00YTY1LTk2MDMtM2U5MTY1NWM1ZTU3";

            // 参数
            boolean isGraduate = true;
            int category = Integer.parseInt(voids[1]);

            String deptId = voids[2];
            int termId = Integer.parseInt(voids[3]);
            String courseCode = "";
            String courseName = "";
            String courseAttribute = "";
            String isSummer = "";
//            if(voids.length > 1 ){
//                category = Integer.parseInt(voids[1]);
//                deptId = voids[2];
//                termId = Integer.parseInt(voids[3]);
//            }

            // 构建查询字符串
            @SuppressLint("DefaultLocale") String query = String.format(
                    "?isGraduate=%b&category=%d&deptId=%s&termId=%d&courseCode=%s&courseName=%s&courseAttribute=%s&isSummer=%s",
                    isGraduate, category, deptId, termId, courseCode, courseName, courseAttribute, isSummer
            );

            // 完整URL
            String fullUrl = url + query;
            StringBuilder response = new StringBuilder();

            try {
                URL obj = new URL(fullUrl);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                // 设置请求方法为GET
                con.setRequestMethod("GET");
                // 在请求头中设置Cookie
                con.setRequestProperty("Cookie", cookie);
                // 获取响应码
                int responseCode = con.getResponseCode();
                Log.d("HTTP Response", "Response Code: " + responseCode);
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String inputLine;

                    while ((inputLine = in.readLine()) != null){
                        response.append(inputLine);
                    }
                    in.close();
//                    boolean startAppending = false;
//
//                    while ((inputLine = in.readLine()) != null) {
//                        if (!startAppending && inputLine.contains("rowspan")) {
//                            startAppending = true;
//                        }
//                        if (startAppending) {
//                            response.append(inputLine);
//                        }
//                    }
//                    in.close();
                } else {
                    Log.e("HTTP Response", "Error in response: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("HTTP Response", "Exception: " + e.getMessage());
            }
            //courses = analysis(response.toString());
            return response.toString();
        }

        private List<String[]> analysis(String toString) {
            // 解析HTML
            Document doc = Jsoup.parse(toString);

            Elements rows_title = doc.select("title");
            String term = term = rows_title.get(0).text().replaceAll("[^\\d]","");
            if(rows_title.get(0).text().contains("秋")){
                term += "-1";
            }else if(rows_title.get(0).text().contains("春")){
                term += "-2";
            }else if(rows_title.get(0).text().contains("夏")){
                term += "-3";
            }

            Elements rows = doc.select("tr");

            // 用于存储解析结果
            List<String[]> courses = new ArrayList<>();

            String courseName = "";
            String teacher = "";

            // 遍历每一行 解析课表
            for (Element row : rows) {
                Elements columns = row.select("td");
                if (columns.size() > 0 && columns.size() <=3) {
                    String weekList = columns.get(0).text();
                    String dayAndTime = columns.get(1).text();
                    String classroom = columns.get(2).text();

                    // 解析周几和节次信息
                    String dayOfWeek = dayAndTime.substring(0, dayAndTime.indexOf('('));
                    String[] times = dayAndTime.substring(dayAndTime.indexOf('(') + 1, dayAndTime.indexOf(')')).split("-");
                    int start = Integer.parseInt(times[0]);
                    int step = Integer.parseInt(times[1]) - start + 1;

                    // 将结果存储到数组中
                    String[] course = {term,courseName, teacher, weekList, dayOfWeek, String.valueOf(step), String.valueOf(start), classroom};
                    courses.add(course);
                }else if( columns.size() >0){
                    courseName = columns.get(3).text();
                    StringBuilder teacherBuilder = new StringBuilder();
                    for (int i = 14; i <= 16; i++) {
                        String t = columns.get(i).text();
                        if (!t.isEmpty()) {
                            if (teacherBuilder.length() > 0) {
                                teacherBuilder.append(", ");
                            }
                            teacherBuilder.append(t);
                        }
                    }
                    teacher = teacherBuilder.toString();
                    String weekList = columns.get(9).text();
                    String dayAndTime = columns.get(10).text();
                    String classroom = columns.get(11).text();

                    // 解析周几和节次信息
                    String dayOfWeek = dayAndTime.substring(0, dayAndTime.indexOf('('));
                    String[] times = dayAndTime.substring(dayAndTime.indexOf('(') + 1, dayAndTime.indexOf(')')).split("-");
                    int start = Integer.parseInt(times[0]);
                    int step = Integer.parseInt(times[1]) - start + 1;

                    // 将结果存储到数组中
                    String[] course = {term,courseName, teacher, weekList, dayOfWeek, String.valueOf(step), String.valueOf(start), classroom};
                    courses.add(course);
                }
            }
            Elements categoryOptions = doc.select("select#category > option");

            for (Element option : categoryOptions) {
                categoryList.add(option.text());
            }
            // 解析 deptId
            Elements deptIdOptions = doc.select("select#deptId > option");
            for (Element option : deptIdOptions) {
                depIdList.add(option.text());
            }
            // 解析 termId
            Elements termIdOptions = doc.select("select[name=termId] > option");
            for (Element option : termIdOptions) {
                termList.add(option.text());
            }
            return courses;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println(result);
            courses = analysis(result);
            mySubjects.clear();
            Subjects_forchoose.clear();
            for(String[] str :courses){
                mySubjects.add(new MySubject(str[0],str[1],str[7],str[2], Utils.getWeekList(str[3]), Integer.parseInt(str[6]),Integer.parseInt(str[5]),Utils.changeDayofWeek(str[4]),-1,null));
                Subjects_forchoose.add(new MySubject(str[0],str[1],str[7],str[2], Utils.getWeekList(str[3]), Integer.parseInt(str[6]),1,Utils.changeDayofWeek(str[4]),-1,null));
            }
            Log.d("HTTP Response", "Page Content: " + result);
        }
    }

    private void showPopmenu() {
        PopupMenu popup = new PopupMenu(this, button);
        popup.getMenuInflater().inflate(R.menu.popmenu_data, popup.getMenu());
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @SuppressLint("NonConstantResourceId")
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.top1:
                        hideDateView();
                        break;
                    case R.id.top2:
                        showDateView();
                        break;
                    case R.id.top3:
                        customDateView();
                        break;
                    case R.id.top4:
                        cancelCustomDateView();
                        break;
                    case R.id.top5:
                        showAddSubjectDialog();
                        break;
                    case R.id.top6:
                        chooceAllSubject();
                        break;
                    case R.id.top7:
                        initTimetableView(chooseSubjects);
                        break;
                    case R.id.top8:
                        toparasAvtivity();
                        break;
                    case R.id.top9:
                        showTheSignal();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
        popup.show();
    }

    private void toparasAvtivity() {
        Intent intent = new Intent(getBackActivity.this, parasActivity.class);
        startActivity(intent);
    }

    private  void showTheSignal(){
        Intent intent=new Intent(getBackActivity.this,getSignalActivity.class);
        startActivity(intent);
    }

    private void showInputDialog() {
        // 创建对话框构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Input Dialog");

        // 从布局资源中加载对话框布局
        final View customLayout = getLayoutInflater().inflate(R.layout.subject_dialog_input, null);
        builder.setView(customLayout);

        Spinner spinner1 = customLayout.findViewById(R.id.categorySpinner);
        Spinner spinner2 = customLayout.findViewById(R.id.deptIdSpinner);
        Spinner spinner3 = customLayout.findViewById(R.id.termIdSpinner);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,categoryList);

        //ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.options1, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter1);

        //ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,R.array.options2_default, android.R.layout.simple_spinner_item);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,depIdList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter2);

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateSpinner2Options(spinner1.getSelectedItem().toString(), spinner2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });

        //ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.options3, android.R.layout.simple_spinner_item);
        ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,termList);
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner3.setAdapter(adapter3);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String selection1 = spinner1.getSelectedItem().toString();
                String selection2 = spinner2.getSelectedItem().toString();
                String selection3 = spinner3.getSelectedItem().toString();

                handleSelection(selection1, selection2, selection3);
            }
        });

        builder.setNegativeButton("Cancel", null);

        // 显示对话框
        builder.show();
    }

    private void updateSpinner2Options(String selectedOption1, Spinner spinner2) {
        int optionsArrayId;
        switch (selectedOption1) {
            case "京内院系":
                optionsArrayId = R.array.options2_for_option1;
                break;
            case "研究所":
                optionsArrayId = R.array.options2_for_option2;
                break;
            case "京外学院":
                optionsArrayId = R.array.options2_for_option3;
                break;
            case "基地":
                optionsArrayId = R.array.options2_for_option4;
                break;
            default:
                optionsArrayId = R.array.options2_default;
                break;
        }
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, optionsArrayId, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter2);
    }

    private void handleSelection(String selection1, String selection2, String selection3) {

    }

    /**
     * 选择课程
     */
    private void chooceAllSubject() {
        String COL_1 = "ID";
        String COL_2 = "NAME";
        String COL_3 = "TEACHER";
        String COL_4 = "ROOM";
        String COL_5 = "WEEKLIST";
        String COL_6 = "START";
        String COL_7 = "STEP";
        String COL_8 = "DAY";
        String COL_9 = "TAG";
        String COL_10 = "TERM";
        //mTimetableView.source(mySubjects).updateView();
        setNonThisWeekBgcolor(R.color.app_blue1);
        mWeekView.source(Subjects_forchoose).updateView();
        mTimetableView.callback(new ISchedule.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, List<Schedule> scheduleList) {
                        String []items =new String[scheduleList.size()];
                        for(int i=0;i<scheduleList.size();i++){
                            items[i] = scheduleList.get(i).getName();
                        }
                        AlertDialog.Builder builder =new AlertDialog.Builder(getBackActivity.this);
                        builder.setTitle("选择你的课程");
                        builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                target = i;
                            }
                        });
                        builder.setPositiveButton("确定课程", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {
                                if(target == -1)
                                    target+=1;
                                MySubject ms = new MySubject("",scheduleList.get(target).getName(),scheduleList.get(target).getRoom(),scheduleList.get(target).getTeacher(),scheduleList.get(target).getWeekList(),scheduleList.get(target).getStart(),scheduleList.get(target).getStep(),scheduleList.get(target).getDay(),scheduleList.get(target).getColorRandom(),null);
                                chooseSubjects.add(ms);
                                Subjects_database.insertData(ms.getName(),ms.getTeacher(),ms.getRoom(),ms.getWeekList().stream().map(Objects::toString).collect(Collectors.joining(",")), ms.getStart(),ms.getStep(),ms.getDay(),0,ms.getTerm());
                                Subjects_database.checkAndMarkConflicts();
                            }
                        });

                        builder.setNegativeButton("取消", null);
                        builder.create().show();
                    }
                })

                .curWeek(1)
                .isShowNotCurWeek(true)
                .source(Subjects_forchoose).showView();
    }


    /**
     * 课程添加
     */
    private void showAddSubjectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加课程");

        View view = getLayoutInflater().inflate(R.layout.dialog_add_subject, null);
        builder.setView(view);

        EditText etSubjectName = view.findViewById(R.id.et_subject_name);
        EditText etTeacherName = view.findViewById(R.id.et_teacher_name);
        EditText etRoom = view.findViewById(R.id.et_room);
        EditText etWeeklist = view.findViewById(R.id.et_weeklist);
        EditText etStart = view.findViewById(R.id.et_start);
        EditText etStep = view.findViewById(R.id.et_step);
        EditText etDay = view.findViewById(R.id.et_day);
        EditText etTerm = view.findViewById(R.id.et_term);

        builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String subjectName = etSubjectName.getText().toString().trim();
                String teacherName = etTeacherName.getText().toString().trim();
                String room = etRoom.getText().toString().trim();
                String weeklist = etWeeklist.getText().toString().trim();
                String startStr = etStart.getText().toString().trim();
                String stepStr = etStep.getText().toString().trim();
                String dayStr = etDay.getText().toString().trim();
                String term = etTerm.getText().toString().trim();

                if (subjectName.isEmpty() || teacherName.isEmpty() || room.isEmpty() || weeklist.isEmpty() ||
                        startStr.isEmpty() || stepStr.isEmpty() || dayStr.isEmpty() || term.isEmpty()) {
                    Toast.makeText(getBackActivity.this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                    return;
                }

                int start = Integer.parseInt(startStr);
                int step = Integer.parseInt(stepStr);
                int day = Integer.parseInt(dayStr);

                Toast.makeText(getBackActivity.this, "课程添加成功", Toast.LENGTH_SHORT).show();
                mySubjects.add(new MySubject(term,subjectName,room,teacherName, Arrays.stream(weeklist.split(",")).map(Integer::parseInt).collect(Collectors.toList()), start,step,day,-1,null));
//                boolean isInserted = Subjects_database.insertData(subjectName, teacherName, room, weeklist, start, step, day, 0, term);
//                if (isInserted) {
//                    Toast.makeText(getBackActivity.this, "课程添加成功", Toast.LENGTH_SHORT).show();
//                    mySubjects.add(new MySubject(term,subjectName,room,teacherName, Arrays.stream(weeklist.split(",")).map(Integer::parseInt).collect(Collectors.toList()), start,step,day,-1,null));
//                    //mTimetableView.source(mySubjects).showView();
//                    //mWeekView.source(mySubjects).showView();
//                } else {
//                    Toast.makeText(getBackActivity.this, "课程添加失败", Toast.LENGTH_SHORT).show();
//                }
            }
        });

        builder.setNegativeButton("取消", null);

        builder.create().show();
    }

    /**
     * 隐藏日期栏
     */
    protected void hideDateView() {
        mTimetableView.hideDateView();
    }

    /**
     * 显示日期栏
     */
    protected void showDateView() {
        mTimetableView.showDateView();
    }

    /**
     * 自定义日期栏
     * 该段代码有点长，但是很好懂，仔细看看会有收获的，嘻嘻
     */
    protected void customDateView() {
        mTimetableView.callback(
                        new OnDateBuildAapter() {
                            @Override
                            public View onBuildDayLayout(LayoutInflater mInflate, int pos, int width, int height) {
                                int newHeight= ScreenUtils.dip2px(getBackActivity.this,30);
                                View v = mInflate.inflate(R.layout.item_custom_dateview, null, false);
                                TextView dayTextView = v.findViewById(R.id.id_week_day);
                                dayTextView.setText(dateArray[pos]);
                                layouts[pos] = v.findViewById(R.id.id_week_layout);

                                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, newHeight);
                                layouts[pos].setLayoutParams(lp);

                                return v;
                            }

                            @Override
                            public View onBuildMonthLayout(LayoutInflater mInflate, int width, int height) {
                                int newHeight=ScreenUtils.dip2px(getBackActivity.this,30);
                                View first = mInflate.inflate(R.layout.item_custom_dateview_first, null, false);
                                //月份设置
                                textViews[0] = first.findViewById(R.id.id_week_month);
                                layouts[0] = null;

                                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, newHeight);

                                int month = Integer.parseInt(weekDates.get(0));
                                first.setLayoutParams(lp);
                                textViews[0].setText(month + "\n月");
                                return first;

                            }
                        })
                .updateDateView();
    }

    /**
     * 恢复默认日期栏
     */
    protected void cancelCustomDateView() {
        mTimetableView.callback((ISchedule.OnDateBuildListener) null)
                .updateDateView();
    }

    /**
     * 2秒后刷新界面，模拟网络请求
     */
    private void requestData() {
        alertDialog=new AlertDialog.Builder(this)
                .setMessage("获取网页信息中..")
                .setTitle("Loading...").create();
        alertDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(0x123);
            }
        }).start();
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(alertDialog!=null)
                alertDialog.hide();
        }
    };
    /**
     * 初始化课程控件
     */
    private void initTimetableView(List<MySubject> chooseSubjects) {
        //获取控件
        mWeekView = findViewById(R.id.id_weekview);
        mTimetableView = findViewById(R.id.id_timetableView);

        mTimetableView.source(chooseSubjects)
                .curWeek("2024-05-06 00:00:00")
                .callback(new ISchedule.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v, List<Schedule> scheduleList) {
                        display(scheduleList);

                    }
                })
                .callback(new ISchedule.OnItemLongClickListener() {
                    @Override
                    public void onLongClick(View v, int day, int start) {
                        Toast.makeText(getBackActivity.this,
                                "周" + day  + " 第" + start + "节",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .callback(getDateDelayAdapter())
                .callback(new ISchedule.OnWeekChangedListener() {
                    @Override
                    public void onWeekChanged(int curWeek) {
                        OnDateDelayAdapter adapter= (OnDateDelayAdapter) mTimetableView.onDateBuildListener();
                        long when=adapter.whenBeginSchool();
                        if(when>0){
                            titleTextView.setText("距离开学还有"+when+"天");
                        }else{
                            titleTextView.setText("第" + curWeek + "周");
                        }
                    }
                })
                .isShowNotCurWeek(false)
                .showView();
        //设置周次选择属性
        mWeekView.source(chooseSubjects)
                .curWeek(mTimetableView.curWeek())
                .callback(new IWeekView.OnWeekItemClickedListener() {
                    @Override
                    public void onWeekClicked(int week) {
                        int cur = mTimetableView.curWeek();
                        //更新切换后的日期，从当前周cur->切换的周week
                        mTimetableView.onDateBuildListener()
                                .onUpdateDate(cur, week);
                        mTimetableView.changeWeekOnly(week);
                    }
                })
                .callback(new IWeekView.OnWeekLeftClickedListener() {
                    @Override
                    public void onWeekLeftClicked() {
                        onWeekLeftLayoutClicked();
                    }
                })
                .isShow(false)//设置隐藏，默认显示
                .showView();

    }

    /**
     * 配置OnDateDelayAdapter
     */
    public OnDateDelayAdapter getDateDelayAdapter(){
        OnDateDelayAdapter onDateDelayAdapter=new OnDateDelayAdapter();

        //计算开学时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long startTime=0;
        try {
            startTime=sdf.parse("2024-05-06 00:00:00").getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //计算开学时的一周日期
        List<String> dateList= Arrays.asList("5","06","07","08","09","10","11","12");

        //设置
        onDateDelayAdapter.setStartTime(startTime);
        onDateDelayAdapter.setDateList(dateList);
        return onDateDelayAdapter;
    }

    /**
     * 修改显示的文本
     */
    public void buildItemText() {
        mTimetableView.callback(new OnItemBuildAdapter() {
                    @Override
                    public String getItemText(Schedule schedule, boolean isThisWeek) {
                        if (isThisWeek)
                            return "[本周]" + schedule.getName() + "@" +schedule.getRoom();

                        return "非本周" + schedule.getName() + "@" +schedule.getRoom();
                    }
                })
                .updateView();
    }


    @Override
    protected void onStart() {
        super.onStart();
//        mTimetableView.onDateBuildListener()
//                .onHighLight();
        //用于更正日期的显示
        int cur=mTimetableView.curWeek();
        mTimetableView.onDateBuildListener().onUpdateDate(cur,cur);

        //更新文本
        OnDateDelayAdapter adapter= (OnDateDelayAdapter) mTimetableView.onDateBuildListener();
        long when=adapter.whenBeginSchool();
        if(when>0){
            titleTextView.setText("距离开学还有"+when+"天");
        }
    }

    /**
     * 设置非本周课的背景
     *
     * @param color
     */
    public void setNonThisWeekBgcolor(int color) {
        mTimetableView.colorPool().setUselessColor(color);
        mTimetableView.updateView();
    }

    /**
     * 隐藏非本周课程
     * 修改了内容的显示，所以必须更新全部（性能不高）
     * 建议：在初始化时设置该属性
     */
    protected void hideNonThisWeek() {
        mTimetableView.isShowNotCurWeek(false).updateView();
    }

    /**
     * 显示非本周课程
     * 修改了内容的显示，所以必须更新全部（性能不高）
     * 建议：在初始化时设置该属性
     */
    protected void showNonThisWeek() {
        mTimetableView.isShowNotCurWeek(true).updateView();
    }

    /**
     * 周次选择布局的左侧被点击时回调<br/>
     * 对话框修改当前周次
     */
    protected void onWeekLeftLayoutClicked() {
        final String items[] = new String[20];
        int itemCount = mWeekView.itemCount();
        for (int i = 0; i < itemCount; i++) {
            items[i] = "第" + (i + 1) + "周";
        }
        target = -1;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置当前周");
        builder.setSingleChoiceItems(items, mTimetableView.curWeek() - 1,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        target = i;
                    }
                });
        builder.setPositiveButton("设置为当前周", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (target != -1) {
                    mWeekView.curWeek(target + 1).updateView();
                    mTimetableView.changeWeekForce(target + 1);
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    /**
     * 显示内容
     *
     * @param beans
     */
    protected void display(List<Schedule> beans) {
        String str = "";
        for (Schedule bean : beans) {
            str += bean.getName() + ","+bean.getTeacher()+","+bean.getRoom()+"\n";
        }
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_layout:
                //如果周次选择已经显示了，那么将它隐藏，更新课程、日期
                //否则，显示
                if (mWeekView.isShowing()) hideWeekView();
                else showWeekView();
                break;
        }
    }

    /**
     * 隐藏周次选择，此时需要将课表的日期恢复到本周并将课表切换到当前周
     */
    public void hideWeekView(){
        mWeekView.isShow(false);
        titleTextView.setTextColor(getResources().getColor(R.color.app_course_textcolor_blue));
        int cur = mTimetableView.curWeek();
        mTimetableView.onDateBuildListener()
                .onUpdateDate(cur, cur);
        mTimetableView.changeWeekOnly(cur);
    }

    public void showWeekView(){
        mWeekView.isShow(true);
        titleTextView.setTextColor(getResources().getColor(R.color.app_red));
    }

}
